package com.lanhao.aot.nettyudp;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author liumengqi
 */
public class UdpSendClient {
    private static Logger logger = LoggerFactory.getLogger(UdpSendClient.class);

    private static class ClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
            System.out.println("channelRead0");
        }
    }

    public void sendToGateway(String ip, int port, String body) {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioDatagramChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ClientHandler());

            ChannelFuture future = b.connect(ip, port).sync();
            future.channel().writeAndFlush(Unpooled.copiedBuffer(body, CharsetUtil.UTF_8)).addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    boolean success = future.isSuccess();
                    logger.info("success={}", success);
                }
            });
            logger.info("sendToGateway......body={}", body);
            future.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("sendToGateway, An Error Occur ==>" + e);
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        UdpSendClient udpClient = new UdpSendClient();
        String sendBody = "{\"mac\":\"111\",\"deviceId\":\"111\", \"pin\",\"222\"}";
        udpClient.sendToGateway("192.168.31.233", 23402, sendBody);
    }
}